<script lang="ts" setup>
import {
  ElTable,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElMessageBox,
  ElRow,
  ElCol,
  ElPagination,
  ElMessage,
  ElTreeSelect,
} from "element-plus";
import { ref, onMounted } from "vue";
import { Plus } from "@vben/icons";
import { router } from "#/router";
import {
  getAirportList,
  deleteAirport,
  edit,
  getMqtt,
} from "#/api/sys/equipment";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import { useDebounceFn } from "@vueuse/core";
import SettingInfo from "./settingInfo.vue";

const status = ref("");
const airportName = ref("");
const organizationId = ref();
const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const treeData = ref([]);
const settingInfoRef = ref();
const defaultProps = {
  children: "children",
  label: "organizationName",
};

// 编辑状态管理 - 合并为一个对象管理所有编辑状态
const editingState = ref({
  id: null,
  airportName: "",
  organizationId: "",
});

// 统一的编辑开始方法（双击任一字段都会进入编辑状态）
const startEdit = (row) => {
  editingState.value = {
    id: row.id,
    airportName: row.airportName,
    organizationId: row.organizationId,
  };
};

// 统一的取消编辑方法
const cancelEdit = () => {
  editingState.value = {
    id: null,
    airportName: "",
    organizationId: "",
  };
};

// 保存编辑内容（同时保存两个字段）
const saveEdit = async (row) => {
  // 验证必填字段
  if (!editingState.value.airportName.trim()) {
    ElMessage.warning("机场名称不能为空");
    return;
  }

  if (!editingState.value.organizationId) {
    ElMessage.warning("请选择所属组织");
    return;
  }

  try {
    const params = {
      id: row.id,
      airportName: editingState.value.airportName.trim(),
      organizationId: editingState.value.organizationId,
    };

    const { code, msg } = await edit(params);
    if (code === 200) {
      ElMessage.success("修改成功");
      // 更新表格数据
      row.airportName = editingState.value.airportName.trim();
      row.organizationId = editingState.value.organizationId;
      // 更新组织名称显示
      const org = findOrganizationName(
        editingState.value.organizationId,
        treeData.value
      );
      row.organizationName = org ? org.organizationName : "";
      search();
      cancelEdit();
    } else {
      ElMessage.error(msg);
    }
  } catch (error) {
    ElMessage.error(`修改失败: ${error.message || "未知错误"}`);
    console.error("修改机场信息失败:", error);
  }
};

const handleNameInput = (value) => {
  editingState.value.airportName = value.replace(/\s+/g, "");
};
const search = async () => {
  // 将organizationId数组转换为逗号分隔的字符串
  const organizationIdsStr = Array.isArray(organizationId.value)
    ? organizationId.value.join(",")
    : organizationId.value;

  const params = {
    airportName: airportName.value,
    status: status.value,
    organizationIds: organizationIdsStr,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  const { data } = await getAirportList(params);
  if (data.records.length > 0) {
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
};
const debouncedSearch = useDebounceFn(search, 500);
const resetForm = () => {
  status.value = "";
  airportName.value = "";
  organizationId.value = [];
  currentPage.value = 1;
  search();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

const statusOptions = [
  {
    label: "在线",
    value: 1,
  },
  {
    label: "离线",
    value: 2,
  },
];

const addItem = () => {
  router.push({
    name: "AirportAddEdit",
  });
};
const editItem = (row) => {
  router.push({
    name: "AirportAddEdit",
    query: {
      id: row.id,
    },
  });
};
const detailItem = (row) => {
  router.push({
    name: "AirportDetail",
    query: {
      id: row.id,
    },
  });
};
const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `删除将会导致相关计划失效，确定删除机场【${row.airportName}】吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteAirport(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除机场失败:", error);
    }
  }
};

const spaceInput = (value: string) => {
  // 过滤空格
  airportName.value = value.replace(/\s+/g, "");
};

// 递归查找组织名称
const findOrganizationName = (orgId, orgList) => {
  for (const org of orgList) {
    if (org.id === orgId) {
      return org;
    }
    if (org.children && org.children.length > 0) {
      const found = findOrganizationName(orgId, org.children);
      if (found) return found;
    }
  }
  return null;
};

const getOrganizationsList = async () => {
  const { data } = await getOrganizationsByUserId();
  treeData.value = data;
};

// 为树节点添加title属性
const getNodeTitle = (data) => {
  return data.organizationName || "";
};
// 显示机场配置信息弹窗
const showSettingInfo = async () => {
  const { data } = await getMqtt({ orgId: 1 });
  settingInfoRef.value.openDialog(data);
};

onMounted(() => {
  search();
  getOrganizationsList();
});
</script>

<template>
  <div class="page pageStyle">
    <div class="search">
      <ElRow>
        <ElCol :xs="24" :sm="24" :md="20" :lg="20" :xl="20" class="searchCol">
          <div class="searchForm">
            <div>
              <span>机场名称：</span>
              <ElInput
                v-model="airportName"
                style="width: 240px; margin-right: 20px"
                placeholder="请输入机场名称"
                @input="spaceInput"
              />
            </div>
            <!-- <div>
              <span>机场状态：</span>
              <ElSelect
                v-model="status"
                placeholder="请选择机场状态"
                @change="search()"
                style="width: 240px; margin-right: 20px"
              >
                <ElOption
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </div> -->
            <div>
              <span>所属组织：</span>
              <ElTreeSelect
                v-model="organizationId"
                :data="treeData"
                :props="defaultProps"
                check-strictly
                node-key="id"
                multiple
                collapse-tags
                placeholder="请选择组织"
                style="width: 200px; margin-right: 20px"
              >
                <!-- 自定义树节点内容，添加title属性 -->
                <template #default="{ node, data }">
                  <span :title="getNodeTitle(data)" class="el-tree-node__label">
                    {{ data.organizationName }}
                  </span>
                </template>
              </ElTreeSelect>
            </div>
            <div class="searchBtn">
              <ElButton type="primary" @click="debouncedSearch">查询</ElButton>
              <ElButton @click="resetForm">重置</ElButton>
            </div>
          </div>
        </ElCol>
        <ElCol :xs="24" :sm="24" :md="4" :lg="4" :xl="4" class="searchCol">
          <div style="float: right">
            <!-- <ElButton type="primary" @click="addItem">添加</ElButton> -->
            <ElButton type="primary" @click="showSettingInfo"
              >配置机场</ElButton
            >
          </div>
        </ElCol>
      </ElRow>
    </div>
    <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
      <ElTable.TableColumn
        prop="airportName"
        label="机场名称"
        align="left"
        width="280"
      >
        <template #default="scope">
          <div
            v-if="editingState.id === scope.row.id"
            class="edit-name-container"
          >
            <ElInput
              v-model="editingState.airportName"
              @input="handleNameInput"
              @keyup.enter="saveEdit(scope.row)"
              @keyup.esc="cancelEdit"
              size="small"
              maxlength="50"
              show-word-limit
              type="textarea"
              autosize
              style="width: 280px"
            />
          </div>
          <!--<div v-else class="name-display" @dblclick="startEdit(scope.row)">
            {{ scope.row.airportName }}
            <span class="edit-tip">（双击编辑）</span>
          </div> -->
        </template>
      </ElTable.TableColumn>
      <ElTable.TableColumn
        prop="organizationName"
        label="所属组织"
        align="left"
        width="200"
      >
        <template #default="scope">
          <div
            v-if="editingState.id === scope.row.id"
            class="edit-org-container"
          >
            <ElTreeSelect
              v-model="editingState.organizationId"
              :data="treeData"
              :props="{
                children: 'children',
                label: 'organizationName',
                disabled: (data) => data.status === false || data.disabled == 1,
              }"
              check-strictly
              node-key="id"
              placeholder="请选择组织"
              style="width: 200px"
              size="small"
            />
          </div>
          <!--<div v-else class="org-display" @dblclick="startEdit(scope.row)">
            {{ scope.row.organizationName || "未设置" }}
            <span class="edit-tip">（双击编辑）</span>
          </div> -->
        </template>
      </ElTable.TableColumn>
      <ElTable.TableColumn prop="gatewaySn" label="设备SN码" align="center" />
      <ElTable.TableColumn
        prop="firmwareVersion"
        label="固件版本"
        align="center"
      >
        <template #default="scope">
          <p
            v-if="scope.row.firmwareUpgradeStatus == 1"
            @click="detailItem(scope.row)"
          >
            {{ scope.row.firmwareVersion }}
            <span style="color: #f56c6c">可升级</span>
          </p>
          <p v-else @click="detailItem(scope.row)">
            {{ scope.row.firmwareVersion }}
          </p>
        </template>
      </ElTable.TableColumn>
      <!-- <ElTable.TableColumn prop="description" label="机场描述" align="center" show-overflow-tooltip/> -->
      <ElTable.TableColumn
        prop="status"
        label="机场状态"
        align="center"
        width="90"
      >
        <template #default="scope">
          <span v-if="scope.row.status == '在线'" style="color: #67c23a"
            >在线</span
          >
          <span v-if="scope.row.status == '离线'" style="color: #f56c6c"
            >离线</span
          >
        </template>
      </ElTable.TableColumn>
      <!-- <ElTable.TableColumn
        prop="maintenance"
        label="保养信息"
        align="center"
        width="90"
      >
        <template #default="scope">
          <span v-if="scope.row.maintenance == '无需保养'" style="color: #67c23a"
            >无需保养</span
          >
          <span v-if="scope.row.maintenance == '待保养'" style="color: #f56c6c"
            >待保养</span
          >
          <span v-if="scope.row.maintenance == '正在保养'" style="color: var(--el-color-primary)"
            >正在保养</span
          >
        </template>
      </ElTable.TableColumn> -->
      <ElTable.TableColumn
        prop="droneNums"
        label="关联无人机数量"
        align="center"
        width="130"
      />
      <!-- <ElTable.TableColumn
        prop="environmentThreshold"
        label="环境阈值"
        align="center"
      /> -->
      <ElTable.TableColumn fixed="right" label="操作" align="center">
        <template #default="scope">
          <!-- 编辑状态时显示保存和取消按钮 -->
          <div v-if="editingState.id === scope.row.id" class="edit-actions">
            <img
              src="/static/mediaList/img/dui.png"
              alt="保存"
              @click="saveEdit(scope.row)"
              class="img-save"
              style="margin-right: 20px; cursor: pointer"
            />
            <img
              src="/static/mediaList/img/cuo.png"
              alt="取消"
              @click="cancelEdit"
              class="img-cancel"
              style="cursor: pointer"
            />
          </div>
          <!-- 默认操作按钮 -->
          <div v-else>
            <el-button
              link
              type="primary"
              size="small"
              @click="detailItem(scope.row)"
            >
              详情
            </el-button>
            <!-- @click="editItem(scope.row)" -->
            <el-button
              link
              type="primary"
              size="small"
              @click="startEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="delItem(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </ElTable.TableColumn>
    </ElTable>
    <div class="pagination">
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 机场配置信息弹窗 -->
    <SettingInfo ref="settingInfoRef" />
  </div>
</template>
<style scoped>
.page {
  height: calc(100vh - 188px);
  overflow: scroll;
}

.searchForm {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.el-table {
  margin-top: 20px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.el-table--fit {
  height: calc(100vh - 300px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 0px 16px;
}

@media (max-width: 950px) {
  .searchForm {
    flex-direction: column;
    align-items: flex-start;
  }

  .searchBtn {
    margin-top: 10px;
  }
}

/* 机场名称编辑样式 */
.name-display {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  position: relative;
}

.name-display:hover {
  background-color: #f5f7fa;
}

.name-display:hover .edit-tip {
  opacity: 1;
}

.edit-tip {
  font-size: 12px;
  color: #909399;
  opacity: 0;
  transition: opacity 0.2s;
  margin-left: 8px;
}

.edit-name-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 组织编辑样式 */
.org-display {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  position: relative;
}

.org-display:hover {
  background-color: #f5f7fa;
}

.org-display:hover .edit-tip {
  opacity: 1;
}

.edit-org-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.img-save,
.img-cancel {
  width: 16px;
  height: 16px;
}

.edit-actions {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>